package com.example.myword;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;

import com.example.myword.dao.Word;
import com.example.myword.dao.WordDao;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private AppDatabase db;
    private WordDao wordDao;
    private List<Word> wordList;
    private RecyclerView recyclerView;
    private WordAdapter wordAdapter;
    private String userId = "current_user_id"; // Replace with actual user ID
    private TextView textViewWelcome;
    private TextView buttonExit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 注册广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(DownLoadService.ACTION_DOWNLOAD_COMPLETE);
        filter.addAction(DownLoadService.ACTION_DOWNLOAD_FAILED);
        LocalBroadcastManager.getInstance(this).registerReceiver(downloadReceiver, filter);

        // 获取登录时传递的用户名（这里假设是通过 Intent 传递的）
        String username = getIntent().getStringExtra("username");
        userId = getIntent().getStringExtra("userId");

        textViewWelcome = findViewById(R.id.textViewWelcome);
        textViewWelcome.setText("Welcome, " + username + "!");
        buttonExit = findViewById(R.id.buttonExit);

        db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "word-database").allowMainThreadQueries().build();
        wordDao = db.wordDao();

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        wordList = wordDao.getAllWords(userId);
        wordAdapter = new WordAdapter(wordList);
        recyclerView.setAdapter(wordAdapter);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(view -> showAddWordDialog());
        FloatingActionButton fabStartQuiz = findViewById(R.id.fabStartQuiz);
        fabStartQuiz.setOnClickListener(view -> startQuiz());
        buttonExit.setOnClickListener(v -> exitToLogin());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销广播接收器
        LocalBroadcastManager.getInstance(this).unregisterReceiver(downloadReceiver);
    }

    @Override
    public void onResume() {
        super.onResume();
        wordList = wordDao.getAllWords(userId);
        wordAdapter = new WordAdapter(wordList);
        recyclerView.setAdapter(wordAdapter);
    }

    private void showAddWordDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Add New Word");

        final View customLayout = getLayoutInflater().inflate(R.layout.dialog_add_word, null);
        builder.setView(customLayout);

        TextView buttonDownload = customLayout.findViewById(R.id.buttonDownload);
        //更新词库
//        buttonDownload.setOnClickListener(v -> getWordFromNet());
        buttonDownload.setOnClickListener(v -> startDownloadService());

        builder.setPositiveButton("ADD", (dialog, which) -> {
            EditText wordEditText = customLayout.findViewById(R.id.editTextWord);
            EditText meaningEditText = customLayout.findViewById(R.id.editTextMeaning);
            String word = wordEditText.getText().toString();
            String meaning = meaningEditText.getText().toString();

            Word newWord = new Word();
            newWord.userId = userId;
            newWord.word = word;
            newWord.meaning = meaning;
            newWord.known = false;

            wordDao.insert(newWord);
            wordList.add(newWord);
            wordAdapter.notifyDataSetChanged();
        });

        builder.setNegativeButton("CANCEL", (dialog, which) -> dialog.dismiss());
        builder.create().show();
    }

    private void startQuiz() {
        Intent intent = new Intent(MainActivity.this, QuizActivity.class);
        intent.putExtra("userId", userId);
        startActivity(intent);
    }

    private void exitToLogin() {
        // 跳转回登录页面
        UserPreferences.clearUserPreferences(this);
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
        finish(); // 结束当前活动
    }

    private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (DownLoadService.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
                Toast.makeText(MainActivity.this, "数据获取成功", Toast.LENGTH_SHORT).show();
            } else if (DownLoadService.ACTION_DOWNLOAD_FAILED.equals(intent.getAction())) {
                Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
            }
        }
    };

    // 启动服务的方法
    private void startDownloadService() {
        Intent intent = new Intent(this, DownLoadService.class);
        startService(intent);
    }
}

